package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"vipshop-app/models/mysql"
	"vipshop-app/pkg"

	"vipshop-app/vipshopapc/internal/svc"
	"vipshop-app/vipshopapc/vipshopapc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RefaceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRefaceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefaceLogic {
	return &RefaceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RefaceLogic) Reface(in *vipshopapc.RefaceRequest) (*vipshopapc.RefaceResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在，请先注册")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码输入错误,请重新输入")
	}
	user = mysql.User{
		Model: gorm.Model{
			ID: user.ID,
		},
		Age: int(in.Age),
	}
	err := mysql.DB.Debug().Where("id = ?", user.ID).Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("完善失败")
	}

	return &vipshopapc.RefaceResponse{Id: int64(user.ID)}, nil
}
